from django.db import models
from django.conf import settings

class Conversation(models.Model):
    """
    一次完整会话，可包含多条消息
    """
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, # 跨 app 引用
        on_delete=models.CASCADE,
        related_name="conversations"
    )
    last_message = models.CharField(
        max_length=255,
        blank=True,
        null=True
    )
    title = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.user.username} / #{self.id} {self.title or ''}"


class Message(models.Model):
    ROLE_CHOICES = (
        ("user", "User"),
        ("assistant", "Assistant"),
    )

    conversation = models.ForeignKey(
        Conversation,
        on_delete=models.CASCADE,
        related_name="messages"
    )
    role = models.CharField(max_length=10, choices=ROLE_CHOICES)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    token_cnt = models.IntegerField(null=True, blank=True)  # 可选

    def __str__(self):
        return f"[{self.role}] {self.content[:30]}"


